package ru.artyushov.fingers.main.util;

import ru.artyushov.fingers.core.data.Fingerprint;
import ru.artyushov.fingers.core.data.Point;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Collection;

public class ImageConverters {
    
    private ImageConverters() {}
    
    public static BufferedImage fromFingerprint(Fingerprint fingerprint) {
        BufferedImage bufferedImage = new BufferedImage(
                fingerprint.getColNumber(), fingerprint.getRowNumber(), BufferedImage.TYPE_INT_RGB
        );

        for(int col = 0; col < fingerprint.getColNumber(); col ++) {
            for(int row = 0; row < fingerprint.getRowNumber(); row++) {
                bufferedImage.setRGB(col, row, fingerprint.isFilled(col, row) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
            }
        }


        return bufferedImage;
    }

    public static BufferedImage overlayCircles(BufferedImage image, Collection<Point> points, int radius, int color) {

        for (final Point point : points) {
            for (int x = 0; x <= radius / 2 + 1; x ++) {
                int y = (int) Math.round(Math.sqrt(radius * radius - x * x));

                // first quarter
                setPixel(image, point.x + x, point.y + y, color);
                setPixel(image, point.x + y, point.y + x, color);

                // second quarter
                setPixel(image, point.x - x, point.y + y, color);
                setPixel(image, point.x - y, point.y + x, color);

                // third quarter
                setPixel(image, point.x - x, point.y - y, color);
                setPixel(image, point.x - y, point.y - x, color);

                // fourth quarter
                setPixel(image, point.x + x, point.y - y, color);
                setPixel(image, point.x + y, point.y - x, color);
            }

        }

        return image;
    }

    private static void setPixel(BufferedImage image, int x, int y, int color) {
        if (x >= 0 && x < image.getWidth() && y >= 0 && y < image.getHeight()) {
            image.setRGB(x, y, color);
        }
    }

    public static void showImage(BufferedImage image) {
        final JFrame frame = new JFrame();
        frame.setSize(image.getWidth(), image.getHeight());
        frame.add(new JLabel(new ImageIcon(image)));
        new Thread(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        }).start();
    }
}
